# coding: utf-8

from django.shortcuts import render, HttpResponseRedirect
from django.views import generic
from django.contrib.auth import login, authenticate, logout

from django.contrib.admin.forms import AuthenticationForm


from .forms import LoginForm


class LoginView(generic.View):

    template_name = 'registration/login.html'
    redirect_url = '/dashboard/'

    def get(self, request, *args, **kwargs):
        form = LoginForm(request)
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST)
        if form.is_valid():
            print 'validate '
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect(self.redirect_url)
            error = u'用户名或者密码错误'
            return render(request, self.template_name, {'form': form, "error": error})
        return render(request, self.template_name, {'form': form})


class LogoutView(generic.View):

    redirect_url = '/accounts/login'

    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(self.redirect_url)

